package teleradiologia.repository;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import teleradiologia.domain.Offer;
import teleradiologia.utils.HibernateUtil;

public class OfferDaoImpl implements OfferDao {

	@Override
	public long create(Offer offer) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		long id = (Long) session.save(offer);

		tx.commit();
		session.close();

		return ++id;
	}

	@Override
	public void delete(Offer offer) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		session.delete(offer);

		tx.commit();
		session.close();
	}

	@Override
	public Offer getById(long id) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Offer offer = (Offer) session.get(Offer.class, new Long(id));

		tx.commit();
		session.close();

		return offer;
	}

	@Override
	public void update(Offer offer) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		session.update(offer);

		tx.commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Offer> getAllByManagerdiagnosticlab(String nip) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		List<Offer> offers = session.createQuery(
				"from Offer offer where "
						+ " offer.diagnosticlab=:nip "
						+ " order by offer.id asc").setString("nip", nip)
				.list();

		tx.commit();
		session.close();

		return offers;
	}
}
